package com.luo.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.luo.pojo.po.Books;
import com.luo.pojo.Results;
import com.luo.pojo.query.BookQuery;
import com.luo.service.IBooksService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author luo
 * @since 2025-06-16
 */
@Api(tags = "图书管理接口")
@RestController
@RequestMapping("/books")
@AllArgsConstructor
@CrossOrigin("*")
public class BooksController {
    private final IBooksService booksService;

    @ApiOperation("查图书")
    @GetMapping
    public Results getBooks(@ApiParam("图书名") @RequestParam(required = false) String bookName,
                            @ApiParam("作者名") @RequestParam(required = false) String author) {
        List<Books> booksList = null;
        if (bookName != null || author != null) {
            booksList = booksService.lambdaQuery()
                    .like(StringUtils.isNotBlank(bookName), Books::getBookName, bookName.trim())
                    .or()
                    .like(StringUtils.isNotBlank(author), Books::getAuthor, author.trim())
                    .list();
        } else {
            booksList = booksService.list();
        }

        return Results.success(booksList);
    }

    @ApiOperation("添加图书")
    @PostMapping
    public Results addBooks(@ApiParam("添加的图书") @RequestBody BookQuery book) {
        Books books = BeanUtil.copyProperties(book, Books.class);
        books.setPublicationDate(LocalDate.now());
        booksService.save(books);
        return Results.success();
    }

    @ApiOperation("修改图书信息")
    @PutMapping
    public Results updateBooks(@ApiParam("修改的图书信息") @RequestBody BookQuery book) {
        Books books = BeanUtil.copyProperties(book, Books.class);
        booksService.updateById(books);
        return Results.success();
    }

    @ApiOperation("删除图书")
    @DeleteMapping("/{id}")
    public Results deleteBooks(@ApiParam("要删除的图书id") @PathVariable Integer id) {
        booksService.removeById(id);
        return Results.success();
    }


}
